package elitech.vietnam.myfashion.extend;

import java.util.List;

import android.content.Intent;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper;

import elitech.vietnam.myfashion.LoginActivity;
import elitech.vietnam.myfashion.MainActivity;
import elitech.vietnam.myfashion.R;
import elitech.vietnam.myfashion.config.Const;
import elitech.vietnam.myfashion.dialog.ConnectionErrorDialog;
import elitech.vietnam.myfashion.dialog.OkCancelWarnningDialog;
import elitech.vietnam.myfashion.dialog.QuickAddToCartDialog;
import elitech.vietnam.myfashion.doinbackground.CallServiceTask;
import elitech.vietnam.myfashion.entites.Product;
import elitech.vietnam.myfashion.fragment.DetailFragment;
import elitech.vietnam.myfashion.utilities.Utilities;
import elitech.vietnam.myfashion.widgets.ScaleImageView;

public class GridViewArrayAdapter extends ArrayAdapter<Product> {
	private MainActivity	mContext;
	private boolean			isPadding;

	public GridViewArrayAdapter(MainActivity context, int resource, int textViewResourceId, List<Product> objects, boolean isPadding) {
		super(context, resource, textViewResourceId, objects);
		this.mContext = context;
		this.isPadding = isPadding;
	}

	@Override
	public void notifyDataSetChanged() {
		super.notifyDataSetChanged();
	}

	static class ViewHolder {
		ScaleImageView	image;
		TextView		txtLike, txtName, txtPrice;
		ImageView		tagSaleOff;
		ImageButton		btnCart;
		LinearLayout	layLikes, layPrice;
		// WebView webView;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View row = convertView;
		final Product product = getItem(position);
		final ViewHolder holder;

		if (row == null) {

			LayoutInflater inflater = mContext.getLayoutInflater();
			row = inflater.inflate(R.layout.item_grid, parent, false);
			holder = new ViewHolder();

			holder.image = (ScaleImageView) row.findViewById(R.id.iproduct_image);
			// holder.webView = (WebView) row
			// .findViewById(R.id.iproduct_webView);
			holder.txtLike = (TextView) row.findViewById(R.id.iproduct_txtLikes);
			holder.txtName = (TextView) row.findViewById(R.id.iproduct_txtName);
			holder.txtPrice = (TextView) row.findViewById(R.id.iproduct_txtPrice);
			holder.tagSaleOff = (ImageView) row.findViewById(R.id.iproduct_tagImgSaleOff);
			holder.layPrice = (LinearLayout) row.findViewById(R.id.iproduct_layPrice);
			holder.layLikes = (LinearLayout) row.findViewById(R.id.iproduct_layBtnLike);
			holder.btnCart = (ImageButton) row.findViewById(R.id.iproduct_btnCart);
			row.setTag(holder);
		} else
			holder = (ViewHolder) row.getTag();

		UrlImageViewHelper.setUrlDrawable(holder.image, Const.SERVER_IMAGE_URL + product.Image, R.drawable.loading300);

		// holder.webView.loadUrl("http://eli6.cafe24.com/shopping/images/product/53/1392604571.jpg");

		holder.txtLike.setText(product.Likes + "");
		holder.txtName.setText(product.Name + "");
		holder.txtPrice.setText(Utilities.numberFormat((product.SaleOff != 0) ? product.PriceSale : product.PriceVN) + " VNĐ");
		String color;
		if (product.CategoryColor == null || product.CategoryColor == "" || product.CategoryColor == "#")
			color = "#808080";
		else
			color = product.CategoryColor;

		holder.layPrice.setBackgroundColor(Color.parseColor(color));

		if (product.SaleOff != 0) {
			holder.tagSaleOff.setVisibility(View.VISIBLE);
			int idTag = Utilities.getSaleOffTagId(product.SaleOff);
			if (idTag != 0)
				holder.tagSaleOff.setImageResource(idTag);
		} else {
			holder.tagSaleOff.setVisibility(View.GONE);
		}

		if (product.Liked())
			holder.layLikes.setBackgroundResource(R.drawable.liked);
		else
			holder.layLikes.setBackgroundResource(R.drawable.like);

		holder.image.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (mContext.mDetailFragment == null)
					mContext.mDetailFragment = new DetailFragment();
				if (!mContext.mDetailFragment.isAdded()) {
					mContext.mDetailFragment.setProduct(product);
					mContext.replaceFragment(mContext.mDetailFragment, true);
				}
			}
		});

		holder.layLikes.setOnClickListener(new View.OnClickListener() {
			boolean	isProcessing	= false;

			@Override
			public void onClick(View v) {
				if (!isProcessing) {
					if (mContext.mUser == null) {
						new OkCancelWarnningDialog(mContext, mContext.getString(R.string.requestlogin)) {
							public void onOk() {
								Intent i = new Intent(mContext, LoginActivity.class);
								int mTabId = mContext.mMainPageView.mViewPager.getCurrentItem();
								mTabId = (mTabId == 2) ? 3 : (mTabId == 3) ? 5 : mTabId;
								Log.w("Shopping", "Put ReturnToTab: " + mTabId);
								i.putExtra("ReturnToTab", mTabId);
								mContext.startActivityForResult(i, MainActivity.LOGINACTIVITY);
							};
						}.show();
					} else {
						if (product.Liked()) {
							new OkCancelWarnningDialog(mContext, mContext.getString(R.string.confirmunlikeproduct)) {
								public void onOk() {
									new CallServiceTask() {
										private int	rs	= -2;

										protected void onPreExecute() {
											isProcessing = true;
										};

										public void work() {
											try {
												rs = service.newLike(mContext.mUser.Id, product.Id, product.Liked(), 1);
											} catch (Exception e) {
												e.printStackTrace();
											}
										};

										protected void onPostExecute(Void result) {
											if (rs == -2) {
												if (!mContext.isConnectionErrorShow) {
													mContext.isConnectionErrorShow = true;
													new ConnectionErrorDialog(mContext) {}.show();
												}
											} else if (rs == -1) {
												product.Likes = product.Likes - 1;
												holder.txtLike.setText(product.Likes + "");
												holder.layLikes.setBackgroundResource(R.drawable.like);
												product.Liked = 0;
											} else {
												holder.txtLike.setText(rs + "");
												product.Likes = rs;
												holder.layLikes.setBackgroundResource(R.drawable.like);
												product.Liked = 0;
											}
											isProcessing = false;
										};
									}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
								};
							}.show();
						} else {
							new CallServiceTask() {
								private int	rs	= -2;

								protected void onPreExecute() {
									isProcessing = true;
								};

								public void work() {
									try {
										rs = service.newLike(mContext.mUser.Id, product.Id, product.Liked(), 1);
									} catch (Exception e) {
										e.printStackTrace();
									}
								};

								protected void onPostExecute(Void result) {
									if (rs == -2) {
										if (!mContext.isConnectionErrorShow) {
											mContext.isConnectionErrorShow = true;
											new ConnectionErrorDialog(mContext) {}.show();
										}
									} else if (rs == -1) {
										product.Likes = product.Likes + 1;
										holder.txtLike.setText(product.Likes + "");
										product.Liked = 1;
										holder.layLikes.setBackgroundResource(R.drawable.liked);
									} else {
										holder.txtLike.setText(rs + "");
										product.Likes = rs;
										holder.layLikes.setBackgroundResource(R.drawable.liked);
										product.Liked = 1;
									}
									isProcessing = false;
								};
							}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
						}
					}
				}
			}
		});
		
		holder.btnCart.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				new QuickAddToCartDialog(mContext, product).show();
			}
		});

		if (isPadding)
			row.setPadding(1, 0, 0, 1);
		return row;
	}

}
